<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片式图 -->
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="addRoleDialog = true">添加角色</el-button>
        </el-col>
      </el-row>
      <el-table :data="roleList" border stripe>
        <el-table-column align="center" type="expand">
          <template slot-scope="scope">
            <el-row
              :class="['buttomrow', i1 == 0 ? 'toprow':'']"
              v-for="(item1,i1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 一级权限所在的位置 -->
              <el-col :span="5">
                <el-tag closable @close="removeRightById(scope.row,item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二 三级权限所在的位置 -->
              <el-col :span="19">
                <el-row
                  :class="[i2==0?'':'toprow']"
                  v-for="(item2,i2) in item1.children"
                  :key="item2.id"
                >
                  <!-- 二级权限 -->
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRightById(scope.row,item2.id)"
                    >{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级权限 -->
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      v-for="(item3) in item2.children"
                      :key="item3.id"
                      closable
                      @close="removeRightById(scope.row,item3.id)"
                    >{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column align="center" type="index" label="#"></el-table-column>
        <el-table-column align="center" label="角色名称" prop="roleName"></el-table-column>
        <el-table-column align="center" label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column align="center" label="操作" width="300px">
          <template slot-scope="scope">
            <!-- 编辑按钮 -->
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-edit"
              @click="showEditRoleDialog(scope.row)"
            >编辑</el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              @click="addRoleDelete(scope.row.id)"
            >删除</el-button>
            <el-button
              type="warning"
              size="mini"
              icon="el-icon-setting"
              @click="showSetRightsDialog(scope.row)"
            >分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-dialog
      title="提示"
      :visible.sync="rightsDialogVisible"
      width="30%"
      @close="closeRightsDialog"
    >
      <el-tree
        :default-checked-keys="defKeys"
        :data="rightsList"
        :props="treeProps"
        show-checkbox
        node-key="id"
        default-expand-all
        ref="treeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="rightsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="alotRights">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加角色对话框 -->

    <el-dialog title="添加角色" :visible.sync="addRoleDialog" width="50%" @closed="addRoleClosed">
      <el-form ref="addRoleRef" :model="addRole" label-width="100px" :rules="addRoleRule">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRole.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addRole.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRoleDialog = false">取 消</el-button>
        <el-button type="primary" @click="addRoleButton">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改角色名称对话框 -->
    <el-dialog title="修改角色" :visible.sync="editRoleDialog" width="50%">
      <el-form ref="editRoleRef" :model="editRole" label-width="100px" :rules="addRoleRule">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editRole.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editRole.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="editRoleInfo">确 定</el-button>
        <el-button @click="editRoleDialog = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      roleList: [],
      rightsDialogVisible: false,
      rightsList: [],
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      defKeys: [],
      roleId: '',
      addRoleDialog: false,
      editRoleDialog: false,
      addRole: {
        roleName: '',
        roleDesc: ''
      },
      addRoleRule: {
        roleName: {
          required: true,
          message: '请输入角色名称',
          trigger: 'blur'
        },
        roleDesc: { required: true, message: '请输入角色描述', trigger: 'blur' }
      },
      editRole: {}
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    async getRoleList() {
      const { data: res } = await this.$http.get('roles')
      console.log(res)
      if (res.meta.status !== 200)
        return this.$message.error('获取角色列表失败')
      this.roleList = res.data
    },
    // 删除权限
    async removeRightById(role, rights) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示',
        {
          cancelButtonClass: 'btn-custom-cancel',
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      if (confirmResult !== 'confirm') return this.$message.info('您取消了删除')
      //   console.log('确认了删除')
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${rights}`
      )
      console.log(role)
      if (res.meta.status !== 200) return this.$message.error('删除失败')
      this.$message.success('删除成功')
      role.children = res.data
    },
    // 分配权限处理函数
    async showSetRightsDialog(role) {
      this.roleId = role.id
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200)
        return this.$message.error('获取权限列表失败')
      this.rightsList = res.data
      console.log(this.rightsList)
      this.getLeafKeys(role, this.defKeys)
      this.rightsDialogVisible = true
    },
    //通过递归的形式 获取三级节点的id 并保存在数组defkey数组中
    getLeafKeys(node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }

      node.children.forEach(item => this.getLeafKeys(item, arr))
    },
    closeRightsDialog() {
      this.defKeys = []
    },
    async alotRights() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedNodes()
      ]
      //   console.log(keys)
      const idStr = keys.join(',')
      //   console.log(idStr)
      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        { rids: idStr }
      )
      if (res.meta.status !== 200) return this.$message.error('添加权限失败')
      this.$message.success('分配角色权限成功')
      this.getRoleList()
      this.rightsDialogVisible = false
    },
    addRoleClosed() {
      this.$refs.addRoleRef.resetFields()
    },
    addRoleButton() {
      this.$refs.addRoleRef.validate(async valid => {
        // console.log(this)
        if (!valid) return this.$message.error('请输入完整的信息')
        // console.log(valid)
        const { data: res } = await this.$http.post('roles', this.addRole)
        // 如果添加失败
        if (res.meta.status !== 201) return this.$message.error('添加用户失败')
        this.$message.success('添加用户成功')
        this.addRoleDialog = false
        this.getRoleList()
      })
    },
    // editRoleClosed() {
    //   this.$refs.editRoleRef.resetFields()
    //   //   this.editRoleDialog = false
    // },
    // 请求角色数据
    async showEditRoleDialog(userinfo) {
      const { data: res } = await this.$http.get('roles/' + userinfo.id)
      //   console.log(res)
      if (res.meta.status !== 200) return this.$message.error('获取角色失败')
      this.$message.success('获取角色列表成功')
      this.editRole = res.data
      //   console.log(this.editRole)
      this.editRoleDialog = true
    },
    // 提交修改的角色
    async editRoleInfo() {
      const { data: res } = await this.$http.put(
        'roles/' + this.editRole.roleId,
        this.editRole
      )
      //   console.log(res)
      if (res.meta.status !== 200) return this.$message.error('修改用户新失败')
      this.$message.success('修改用户信息成功')
      // 关闭对话框
      this.editRoleDialog = false
      // 重新请求数据
      this.getRoleList()
    },
    async addRoleDelete(id) {
      // console.log(id)
      const confirmDelete = await this.$confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示',
        {
          cancelButtonClass: 'btn-custom-cancel',
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      if (confirmDelete !== 'confirm') return this.$message.info('已取消删除')
      // 发送请求根据id完成删除动作
      const { data: res } = await this.$http.delete('roles/' + id)
      // 如果删除失败
      if (res.meta.status !== 200) return this.$message.error('删除用户失败')
      // 成功
      this.$message.success('删除成功')
      this.getRoleList()
    }
  }
}
</script>

<style lang="less" scoped>
.el-button {
  margin-bottom: 15px;
}
.el-tag {
  margin: 8px;
}
.toprow {
  border-top: 1px solid #eee;
}
.buttomrow {
  border-bottom: 1px solid #eee;
}
.el-row {
  display: flex;
  align-items: center;
}
</style>